<?php
declare(strict_types=1);

namespace App\Resource\Service\Cook;


use App\Common\Constants\ErrorCode;
use App\Resource\Service\Goods\GoodsBaseService;
use App\Resource\Service\Goods\GoodsMiniService;
use Hyperf\Di\Annotation\Inject;

class CookMiniService extends CookBaseService implements CookServiceInterface
{
    /**
     * @Inject()
     * @var GoodsBaseService
     */
    protected GoodsBaseService $goodsBaseService;

    /**
     * @Inject()
     * @var GoodsMiniService
     */
    protected GoodsMiniService $goodsMiniService;

    /**
     * 业务场景（小程序商品档案详情菜谱推荐）
     * 根据商品ID获取推荐菜谱
     * @param int $id
     * @param int $shop_id
     * @param array|string[] $field
     * @return array
     * @author zhangzhiyuan
     */
    public function getResourceCookById(int $id, int $shop_id): array
    {
        $where = ['status' => self::STATUS];
        $isExist = $this->resourceRedis->exists(self::COOK_LOVE_GOODS_REDIS_KEY . $id);
        if ($isExist) {
            $CookGoodsResultData = unserialize($this->resourceRedis->get(self::COOK_LOVE_GOODS_REDIS_KEY . $id));
        } else {
            $whereRaw ='FIND_IN_SET(' . $id . ',main_materials)';
            $CookBookArr = $this->cookbook->selectList(self::COOKBOOKFIELD,$where,$whereRaw,[],[],1,self::LIMIT,['sort', 'desc']);
            $CookGoodsResultData = [];
            foreach ($CookBookArr as $value) {
                $goodIds =$this->arr->exceptArr(explode(',', $value['main_materials']), $id);
                $CookGoodsResultData[] = [
                    'cook_id' => $value['id'],
                    'title' => $value['title'],
                    'image' => $value['image'],
                    'cook_goods_list' => $this->getResourceCookTimelyArriveGoodsListByIds($shop_id,$goodIds) //待优化
                ];
            }
            $this->resourceRedis->set(self::COOK_LOVE_GOODS_REDIS_KEY . $id, serialize($CookGoodsResultData), self::COOK_LOVE_EXPIRE);
        }
        return ['code' => ErrorCode::SUCCESS, 'data' => array_values($CookGoodsResultData)];
    }

    /**
     * 业务场景（小程序订单推荐菜品）
     * 根据订单商品ids获取推荐菜谱商品
     * @param string $ids
     * @param int $shop_id
     * @param array|string[] $field
     * @return array
     * @author zhangzhiyuan
     */
    public function getResourceCookOrderGoodsListByIds(string $ids, int $shop_id): array
    {
        $cookArr = []; //匹配菜谱
        $where = ['status' => self::STATUS];
        $OrderGoodsIds = explode(',', $ids);
        $combinationNum = md5($ids . $shop_id);  //订单商品组合码
        $isExist = $this->resourceRedis->exists(self::COOK_LOVE_ORDER_GOODS_REDIS_KEY . $combinationNum);
        if ($isExist) {
            $orderLoveGoodsList = unserialize($this->resourceRedis->get(self::COOK_LOVE_ORDER_GOODS_REDIS_KEY . $combinationNum));
        } else {
            foreach ($OrderGoodsIds as $k => $val) {
                $cookList = $this->cookbook->findFirst(self::COOKBOOKFIELD, $where, 'FIND_IN_SET(' . $val . ',main_materials)');
                if (!empty($cookList)) $cookArr[] = $cookList;
            }
            $loveCookGoodIds=$this->getResourceCommonOrderGoodsIds($cookArr,$OrderGoodsIds);
            //匹配推荐有库存菜品档案信息
            $orderLoveGoodsList = $this->getResourceCookTimelyArriveGoodsListByIds($shop_id,$loveCookGoodIds); //待优化
            foreach ($orderLoveGoodsList as $k => $val) {
                if (intval($orderLoveGoodsList[$k]["number_stock"]) < 0) {
                    unset($orderLoveGoodsList[$k]);
                }
            }
            if (!empty($orderLoveGoodsList)) $this->resourceRedis->set(self::COOK_LOVE_ORDER_GOODS_REDIS_KEY . $combinationNum, serialize($orderLoveGoodsList), self::COOK_LOVE_EXPIRE);
        }
        return ['code' => ErrorCode::SUCCESS, 'data' => array_values($orderLoveGoodsList)];
    }

    /**
     * 根据商品ID集合获取及时达商品信息
     * @param int $shop_id
     * @param array $ids
     * @return mixed
     * @author ran
     * @date 2021-03-15 16:04
     * mailbox 466180170@qq.com
     */
    public function getResourceCookTimelyArriveGoodsListByIds(int $shop_id,array $ids): array
    {
        $where =['store_goods.status' =>GoodsBaseService::GOODS_STATUS_1];
        $whereIn =['store_goods.id',$ids];
        $commonCondition=$this->goodsMiniService->getResourceTimelyCommonCondition($shop_id);
        $extraCondition=['where'=>$where,'whereIn'=>$whereIn];
        $needExceptKey= ['sort','kz_goods_id','crd_shop_ids','shop_ids','goods_pick_time','read_pos_stock','safety_stock','image','content','goods_crm_code','read_pos_price','scant_id','ratio','limite_num_per_day'];
        $goodsArray =$this->goodsBaseService->getResourceCommonTimelyArriveGoodsList($needExceptKey,$shop_id,1,20,array_merge($commonCondition,$extraCondition),false);
        return $goodsArray['list'];
    }

}